package com.inspur.resourcequery;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.inspur.common.BaseActivity;
import com.inspur.common.MyApplication;
import com.inspur.common.UserInfo;
import com.inspur.common.domain.RequestInfo;
import com.inspur.common.utils.URLManager;
import com.inspur.common.view.MyEditText;
import com.inspur.common.view.XListView;
import com.inspur.common.view.XListView.IXListViewListener;
import com.inspur.resourcequery.adapter.ResListAdapter;
import com.inspur.resourcequery.model.ResData;
import com.inspur.resourcequery.model.ResRelationData;

public class ResListActivity extends BaseActivity implements IXListViewListener{
	
	// 自定义数据列表
	private XListView mListView = null;
	// 列表适配器
	private ResListAdapter adapter = null;
	// 搜索框
	private MyEditText mEditText = null;
	// 列表适配器中的数据项
	private List<ResData> dataList = new ArrayList<ResData>();
	// 分页查询起始项
	private int start = 0;
	// 每页加载数据量
	private int length = 10;
	// 数据总量
	private int totalCount;
	//总页数
	private int pageCount;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private String resClassEnName;
	private String zh_label;
	private String city_id;
	private String searchType;
	public ResRelationData relation_data;
	public String attri_value;
	public String related_attr;
	private MyApplication application;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (MyApplication)this.getApplication();
		
		setContentView(R.layout.activity_reslist);
		actionBar.setTitle("资源列表");
		
		mListView = (XListView)this.findViewById(R.id.xListView);
		adapter = new ResListAdapter(this, dataList);
		mListView.setAdapter(adapter);
		mListView.setXListViewListener(this);
		mListView.setPullLoadEnable(false);
		
		mListView.setOnItemClickListener(itemClickListener);
		mEditText = (MyEditText)this.findViewById(R.id.search_met);
		mEditText.setOnEditorActionListener(searchListener);
		
		Bundle bundle = this.getIntent().getExtras();
		searchType = bundle.getString("searchType");
		if(searchType.equals("searchByInit")){
			resClassEnName = bundle.getString("resClassEnName");
			zh_label = bundle.getString("zh_label");
			city_id = bundle.getString("city_id");
		}else if(searchType.equals("searchByRelation")){
			ResRelationData relation_data = (ResRelationData)getIntent().getSerializableExtra("relation");
			resClassEnName = relation_data.getRelated_class();
			related_attr = relation_data.getRelated_attr();
			attri_value = relation_data.getAttr_value();
		}
		queryDataList();
	}
	

	/**
	 * 工单列表数据项点击监听事件
	 */
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(ResListActivity.this, ResDetailActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("data", dataList.get(position - 1) );
			bundle.putString("username", application.getUserInfo().getUseraccount());
			intent.putExtras(bundle);
			startActivity(intent);
		}
	};
	
	
	OnEditorActionListener searchListener = new OnEditorActionListener() {
		
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			// TODO Auto-generated method stub
			if (actionId == EditorInfo.IME_ACTION_SEARCH) {
				//显示加载中对话框
				zh_label = mEditText.getText().toString();
				//设置从第一条开始
				start = 0;
				queryDataList();
				
				//隐藏键盘
				InputMethodManager inputMethodManager = 
						(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(
						ResListActivity.this.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				return true;
			}
			return false;
		}
	};
	
//	/**
//	 * 查询按钮监听事件
//	 */
//	OnClickListener searchClickListener = new OnClickListener() {
//		@Override
//		public void onClick(View v) {
//			//显示加载中对话框
//			zh_label = mEditText.getText().toString();
//			//设置从第一条开始
//			start = 0;
//			queryDataList();
//			//点击查询后隐藏输入法
//		    InputMethodManager inputMethodManager = 
//		    		(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//		    inputMethodManager.hideSoftInputFromWindow(
//		    		ResListActivity.this.getCurrentFocus().getWindowToken(),
//		    		InputMethodManager.HIDE_NOT_ALWAYS);
//		}
//	};
	/**
	 * 查询数据列表
	 */
	protected void queryDataList(){
		RequestInfo req = new RequestInfo();
		req.context = ResListActivity.this;
		req.requestUrl = URLManager.URL + URLManager.RES_QUERYPAGE_BYNAME;
		try {
			JSONObject condition = new JSONObject();
			condition.put("ResClassName", resClassEnName);
			if(zh_label!=null && !zh_label.equals("")){
				condition.put("zh_label", zh_label);
			}
			condition.put("pageStart", start);
			condition.put("pageSize", length);
			condition.put("city_id", city_id);
			if(related_attr!= null && attri_value!= null){
				condition.put("related_attr", related_attr);
				condition.put("attri_value", attri_value);
			}
			req.params=condition.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.getDataFromServer(req, new DataCallback<String>() {
			@Override
			public void processData(String paramObject) {
				Log.d("paramObject:",paramObject);
				proccessData(paramObject);
			}

			@Override
			public void getDataFailed() {
				// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

			}

		}, ResListActivity.this);
	}
	public void proccessData(String paramObject){
		try {
			JSONObject jsonObj = new JSONObject(paramObject);
			String message = "";
			if(jsonObj.has("message"))
				message = jsonObj.getString("message")+"";
			if(!message.equals("")){
				Toast.makeText(ResListActivity.this, "加载数据出错:"+message, Toast.LENGTH_SHORT).show();
			}
			totalCount = Integer.parseInt(jsonObj.getString("totalSize"));
			if(start == 0){
				dataList.clear();
			}
			JSONArray resultList = jsonObj.getJSONArray("resultList");
			if(resultList != null && resultList.length() >0){
				for(int i = 0; i < resultList.length(); i++){
					JSONObject obj = resultList.getJSONObject(i);
					ResData data = new ResData();
					data.setResclassenname(resClassEnName);
					if(obj.has("zh_label")){
						data.setName(obj.getString("zh_label"));
					}
					if(obj.has("int_id")){
						data.setInt_id(obj.getString("int_id"));
					}
					if(obj.has("city_id")){
						data.setCity_id(obj.getString("city_id"));
					}
					if(obj.has("city_id_transName")){
						data.setCityName(obj.getString("city_id_transName"));
					}
					if(obj.has("latitude")){
						data.setLatitude(obj.getString("latitude"));
					}
					if(obj.has("longitude")){
						data.setLongitude(obj.getString("longitude"));
					}
					dataList.add(data);
				}
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		adapter.notifyDataSetChanged();
		onLoad();
		
		if(start + length >= totalCount){
			mListView.setPullLoadEnable(false);
		} else {
			mListView.setPullLoadEnable(true);
		}
	}
	@Override
	public void onRefresh() {
		start = 0;
		queryDataList();
	}

	@Override
	public void onLoadMore() {
		start = start + length;
		queryDataList();
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(sdf.format(new Date()));
	}
	
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}

	@Override
	protected void loadViewLayout() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}

}
